import React, { useEffect, useState } from "react";
import { Button, Modal, Space, Table, Form, Input, message } from "antd";
import request from "../../utils/request";
function Index() {
  //定义函数用于渲染列表
  const [data, setData] = useState([]);
  const [count, setCount] = useState();
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(6);
  const [keyword, setKeyword] = useState();
  const ListData = async () => {
    await request
      .get("/article/list", {
        params: {
          page: page, //页码
          pageSize: pageSize, //每页显示条数
          keyword: keyword,
        },
      })
      .then((res) => {
        setData(res.data.rows);
        setCount(res.data.count);
      });
  };
  useEffect(() => {
    ListData();
  }, [count, page, pageSize, keyword]);
  const columns = [
    {
      title: "集合编号",
      dataIndex: "id",
      key: "id",
    },
    {
      title: "集合名称",
      dataIndex: "title",
      key: "title",
    },
    {
      title: "内容体载",
      dataIndex: "content",
      key: "content",
    },
    {
      title: "创建时间",
      dataIndex: "createdAt",
      key: "createdAt",
    },
    {
      title: "操作",
      key: "action",
      render: (_, record) => (
        <Space size="middle">
          <Button type="primary" onClick={() => headEdit(record)}>
            编辑
          </Button>
          <Button type="primary" danger onClick={() => headDetle(record.id)}>
            删除
          </Button>
        </Space>
      ),
    },
  ];
  //分页
  const onChange = (page, pageSize) => {
    console.log(page);
    setPage(page);
    setPageSize(pageSize);
  };
  //模态框
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [form] = Form.useForm();
  const [tit, setTit] = useState();
  const [edit, setEdit] = useState();
  const showModal = () => {
    setIsModalOpen(true);
    setTit("新增");
    form.resetFields();
  };
  const handleOk = () => {
    setIsModalOpen(false);
    form.submit();
  };
  const handleCancel = () => {
    setIsModalOpen(false);
  };
  const headEdit = (values) => {
    setIsModalOpen(true);
    setTit("编辑");
    form.setFieldsValue(values);
    setEdit(values.id);
  };
  const onFinish = async (values) => {
    try {
      const postData = {
        ...values,
        title: values.title, //文章标题
        content: values.content, //文章内容
        tagList: ["HTTP"], //标签  array[string]
        categoryList: ["HTTP"], //分类  array[string]
        authorId: 47529555, //用户id 暂时写死47529555 登陆成功后返回的用户信息
      };
      const headers = {
        headers: {
          Authorization:
            "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6Imp5a2wiLCJ1c2VySWQiOjQ3NTI5NTU1LCJyb2xlIjoxLCJpYXQiOjE3Mzk3OTQyNDIsImV4cCI6MTc0MjM4NjI0Mn0.O7KlsogMjr6YowtOXKGrEaldz5kjKHWQCn3FGvRd1bA",
        },
      };
      if (tit === "新增") {
        await request.post("/article", postData, headers);
      } else {
        await request.put(`/article/${edit}`, postData, headers);
      }
      message.success(`${tit}成功`);
      ListData();
    } catch {
      console.log("操作失败");
    }
  };
  //删除
  const headDetle = (id) => {
    Modal.confirm({
      title: "温馨提示",
      content: "你确定要删除吗？",
      onOk() {
        const newData = data.filter((item) => item.id !== id);
        setData(newData);
        message.success("删除成功");
      },
      onCancel() {
        console.log("Cancel");
      },
    });
  };
  //查询
  const onSearch = (values) => {
    console.log("Success:", values);
    setKeyword(values.keyword);
  };
  //重置
  const [searchform] = Form.useForm();
  const reset = () => {
    searchform.resetFields();
    setKeyword("");
  };
  return (
    <div>
      <Form
        form={searchform}
        layout="inline"
        style={{ maxWidth: 3000 }}
        onFinish={onSearch}
      >
        <Form.Item label="关键字" name="keyword">
          <Input />
        </Form.Item>
        <Form.Item label={null}>
          <Button type="primary" htmlType="submit">
            查询
          </Button>
        </Form.Item>
        <Form.Item label={null}>
          <Button onClick={reset}>重置</Button>
        </Form.Item>
      </Form>
      <Button type="primary" onClick={showModal}>
        新增
      </Button>
      <Table
        columns={columns}
        dataSource={data}
        pagination={{
          total: count,
          showSizeChanger: true,
          showQuickJumper: true,
          onChange: onChange,
        }}
      />
      <Modal
        title={tit}
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <Form form={form} style={{ maxWidth: 600 }} onFinish={onFinish}>
          <Form.Item label="集合名称" name="title">
            <Input />
          </Form.Item>
          <Form.Item label="内容体载" name="content">
            <Input />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
}

export default Index;
